<template>
  <div class="app-container">
    <el-form ref="form" :model="info" label-width="80px">
      <el-row>
        <el-col :span="8" :offset="2">
          <el-form-item label="项目名">
            <el-input v-model="info.project.name" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8" :offset="2">
          <el-form-item label="路线名" v-if="queryParams.routeId != null">
            <el-input v-model="info.route.name" disabled />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="dashboard-editor-container">
      <div class="chart-wrapper">
        <votes-chart :x-axis-data="vote.xAxisData" :y-axis-data="vote.yAxisData" formatter="none" />
      </div>
      <div style="width: 25%;align-self:center">
        <el-form>
          <el-row class="custom-row">
            <el-statistic title="投票人数">
              <template slot="formatter">
                <span style="font-size: xx-large;">{{ analysis.peopleSum}}/</span>
                <span style="font-size: xx-small;">{{ analysis.peopleVoteSum}}</span>
              </template>
            </el-statistic>
          </el-row>
          <el-row class="custom-row">
            <el-statistic :precision="2" group-separator="," :value="analysis.peopleVoteSum>0?analysis.peopleSum/analysis.peopleVoteSum:0" title="投票人数比率"></el-statistic>
          </el-row>
          <el-row class="custom-row">
            <el-statistic :precision="2" group-separator="," :value="analysis.voteSum>0?analysis.peopleSum/analysis.voteSum:0" title="票数比率"></el-statistic>
          </el-row>
          <el-row class="custom-row">
            <el-statistic :precision="2" group-separator="," :value="analysis.peopleSum>0?analysis.dependentSum/analysis.peopleSum:0" title="投票人平均每人携带家属数">
            </el-statistic>
          </el-row>
        </el-form>
      </div>
    </div>


    <h4 class="form-header h4"></h4>

    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="项目" prop="projectId">
        <el-select v-model="queryParams.projectId" placeholder="请选择项目" clearable @change="getRouteOptions">
            <el-option v-for="item in projectOptions" :key="item.id" :label="item.name" :value="item.id"
              :disabled="item.status == 1"></el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="路线" prop="routeIds" v-if="queryParams.routeId == null">
        <el-select v-model="queryParams.routeIds" multiple placeholder="请选择路线" clearable >
            <el-option v-for="item in routeOptions" :key="item.id" :label="item.name" :value="item.id"
              :disabled="item.status == 1"></el-option>
          </el-select>
      </el-form-item>  -->
      <el-form-item label="开始日期" prop="startTime">
        <el-date-picker clearable v-model="queryParams.startTime" type="date" value-format="yyyy-MM-dd"
          :picker-options="startPickerOptions" placeholder="请选择开始日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束日期" prop="endTime">
        <el-date-picker clearable v-model="queryParams.endTime" type="date" value-format="yyyy-MM-dd"
          :picker-options="endPickerOptions" placeholder="请选择结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option :value="0" label="可报名"></el-option>
          <el-option :value="1" label="可补报"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否成团" prop="canGo">
        <el-select v-model="queryParams.canGo" placeholder="请选择状态" clearable>
          <el-option :value="0" label="未成团"></el-option>
          <el-option :value="1" label="已成团"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['lxy:time:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['lxy:time:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="single" @click="handleDelete"
          v-hasPermi="['lxy:time:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['lxy:time:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="timeList" @selection-change="handleSelectionChange"
      @sort-change="handleSortChange" :row-class-name="tableRowClassName">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" v-if="true" />
      <!-- <el-table-column label="路线" align="center" prop="routeId" v-if="queryParams.routeId == null">
      <el-table-column label="编号" align="center" prop="id" v-if="true"/>
      <el-table-column label="路线" align="center" prop="routeId" >
        <template slot-scope="scope">
          <span>{{ routeNameMap[scope.row.routeId] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="开始日期" align="center" prop="startTime" width="180"  sortable>
      </el-table-column> -->
      <el-table-column label="开始日期" align="center" prop="startTime" width="180" sortable="custom">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束日期" align="center" prop="endTime" width="180" sortable="custom">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="总人数" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.count }}/{{ scope.row.max }}</span>
        </template>
      </el-table-column>
      <el-table-column label="职工人数" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.staffCount }}/{{ scope.row.staffMax }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <span>{{ getStatusLabel(scope.row.status) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否成团" align="center" prop="canGo">
        <template slot-scope="scope">
          <span>{{ getCanGoLabel(scope.row.canGo) }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['lxy:time:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['lxy:time:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改时间段对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="项目名">
          <el-input v-model="info.project.name" disabled />
        </el-form-item>
        <el-form-item label="路线名" v-if="queryParams.routeId != null">
          <el-input v-model="info.route.name" disabled />
        </el-form-item>
        <el-form-item label="具体日期" prop="dateRange">
          <el-date-picker clearable v-model="form.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss"
            @change="form.startTime = form.dateRange[0]; form.endTime = form.dateRange[1]">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="人数上限" prop="max">
          <el-input-number v-model="form.max" placeholder="请输入人数上限" controls-position="right" :min="form.count" />
        </el-form-item>
        <el-form-item label="已选人数" prop="count" v-if="form.id != null">
          <el-input v-model="form.count" placeholder="请输入已选人数" disabled />
        </el-form-item>
        <el-form-item label="职工上限" prop="staffMax">
          <el-input-number v-model="form.staffMax" placeholder="请输入职工上限" controls-position="right" :min="form.staffCount"
            :max="form.max" />
        </el-form-item>
        <el-form-item label="已选职工人数" prop="staffCount" v-if="form.id != null">
          <el-input v-model="form.staffCount" placeholder="请输入已选职工人数" disabled />
        </el-form-item>
        <el-form-item label="状态" prop="status" v-if="form.id != null">
          <el-radio-group v-model="form.status" disabled>
            <el-radio :label="0">可报名</el-radio>
            <el-radio :label="1" >可补报</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否成团" prop="canGo" v-if="form.id != null">
          <el-radio-group v-model="form.canGo" disabled>
            <el-radio :label="0">未成团</el-radio>
            <el-radio :label="1">已成团</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTime, getTime, delTime, addTime, updateTime } from "@/api/lxy/time";
import { listProject, getProject } from "@/api/lxy/project";
import { listRoute, getRoute } from "@/api/lxy/route";
import { ifQuestionnaire,voteAnalysisByRoute } from "@/api/lxy/questionnaire";
import VotesChart from '@/views/dashboard/VotesChart'

export default {
  name: "Time",
  components: {
    VotesChart
  },
  data() {
    return {
      //用于将图标中该路线标红
      a: {
        value: undefined,
        itemStyle: {
          color: '#a90000'
        }
      },
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 时间段表格数据
      timeList: [],
      // // 路线选项
      // routeOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //项目路线信息
      info: {
        project: {
        },
        route: {
        },
        questionnaireId: 0
      },
      vote: {
        xAxisData: [],
        yAxisData: [],
        routeList: undefined,
      },
      analysis:{
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,

        projectId: undefined,
        // routeIds: undefined,
        routeId: undefined,

        startTime: undefined,
        endTime: undefined,
        max: undefined,
        count: undefined,
        staffMax: undefined,
        staffCount: undefined,
        canGo: undefined,
        status: undefined,

        orderByColumn: undefined,
        isAsc: undefined,
      },
      // 表单参数
      form: {
      },
      // 表单校验
      rules: {
        id: [
          { required: true, message: "时间段表不能为空", trigger: "blur" }
        ],
        routeId: [
          { required: true, message: "路线不能为空", trigger: "blur" }
        ],
        dateRange: [
          { required: true, message: "日期不能为空", trigger: "blur" }
        ],
        startTime: [
          { required: true, message: "开始日期不能为空", trigger: "blur" }
        ],
        endTime: [
          { required: true, message: "结束日期不能为空", trigger: "blur" }
        ],
        max: [
          { required: true, message: "人数上限不能为空", trigger: "blur" }
        ],
        count: [
          // { required: true, message: "已选人数不能为空", trigger: "blur" }
        ],
        staffMax: [
          { required: true, message: "职工上限不能为空", trigger: "blur" }
        ],
        staffCount: [
          // { required: true, message: "已选职工人数不能为空", trigger: "blur" }
        ],
        canGo: [
          { required: true, message: "是否成团不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
      }
    };
  },
  computed: {
    // // 计算属性，将routeId映射到name
    // routeNameMap() {
    //   const routeNameMap = {};
    //   for (const option of this.routeOptions) {
    //     routeNameMap[option.id] = option.name;
    //   }
    //   return routeNameMap;
    // },
    startPickerOptions() {
      return {
        disabledDate: date => {
          if (this.queryParams.endTime) {
            return date > new Date(this.queryParams.endTime);
          }
          return false; // 不禁用任何日期
        },
      };
    },
    endPickerOptions() {
      // 如果选择了开始日期，则禁用结束日期中早于开始日期的选项
      return {
        disabledDate: date => {
          if (this.queryParams.startTime) {
            return date < new Date(this.queryParams.startTime);
          }
          return false;
        },
      };
    },
  },
  created() {
    this.queryParams.projectId = this.$route.query.projectId;
    this.queryParams.routeId = this.$route.query.routeId;

    //项目信息
    getProject(this.queryParams.projectId).then(response => {
      this.info.project = response.data;
    });

    //路线信息
    getRoute(this.queryParams.routeId).then(response => {
      this.info.route = response.data.agency;
    });

    //判断该项目是否被选为问卷
    // ifQuestionnaire(this.queryParams.projectId).then(response => {
    //   this.info.questionnaireId = response;
    // })

    //问卷图标数据
    listRoute(this.queryParams).then(response => {
      this.vote.routeList = response.rows;
      this.vote.xAxisData = this.vote.routeList.map(item => item.name)

      this.vote.yAxisData = this.vote.routeList.map(item => item.votes)
      for (let i = 0; i < this.vote.routeList.length; i++) {
        if (this.vote.routeList[i].id == this.queryParams.routeId) {
          this.a.value = this.vote.yAxisData[i];
          this.vote.yAxisData[i] = this.a;
        }
      }
    });

    this.getList();

    //问卷该路线数据分析
    voteAnalysisByRoute(this.$route.query.projectId,this.$route.query.routeId).then(response => {  
      this.analysis=response;
    });
  },
  methods: {
    /** 查询时间段列表 */
    getList() {
      this.loading = true;
      listTime(this.queryParams).then(response => {
        this.timeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        routeId: undefined,
        startTime: undefined,
        endTime: undefined,
        remark: undefined,
        max: undefined,
        count: undefined,
        staffMax: undefined,
        staffCount: undefined,
        canGo: undefined,
        status: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined,
        orderByColumn: undefined,
        isAsc: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // 表格升降序
    handleSortChange({ column, prop, order }) {
      let od = undefined;
      if (order === "ascending") {
        od = "asc";
      } else if (order === "descending") {
        od = "desc";
      }
      this.queryParams.orderByColumn = prop;
      this.queryParams.isAsc = od;
      this.queryParams.pageNum = 1;
      this.getList();
    },
    //表格状态颜色显示
    tableRowClassName({ row }) {
      if (row.status == 2) {
        return 'warning-row';
      } else if (row.status == 1) {
        return 'success-row';
      }
      return '';
    },
    // 根据状态值返回相应的标签
    getStatusLabel(status) {
      switch (status) {
        case 0:
          return '可报名';
        case 1:
          return '可补报';
        default:
          return '未知状态';
      }
    },
    // 根据状态值返回相应的标签
    getCanGoLabel(canGo) {
      switch (canGo) {
        case 0:
          return '未成团';
        case 1:
          return '已成团';
        default:
          return '未知状态';
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      if (this.info.route.type > 2) {
        this.$modal.msgWarning("仅已通过和选为问卷的路线可以添加时间段！");
        return;
      }
      this.reset();
      this.open = true;
      this.title = "添加时间段";
      this.form.projectId = this.queryParams.projectId;
      this.form.routeId = this.queryParams.routeId;
      this.form.canGo = 0;
      this.form.status = 0;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      if (row.canGo !== 0) {
        this.$modal.msgWarning("该时间段已经成团，不可再修改！");
        return;
      }
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getTime(id).then(response => {
        this.loading = false;
        this.form = response.data;
        //修改页面获取日期范围dateRange
        if (!Array.isArray(this.form.dateRange)) {
          this.form.dateRange = [null, null];
        }
        this.form.dateRange[0] = this.form.startTime;
        this.form.dateRange[1] = this.form.endTime;
        this.open = true;
        this.title = "修改时间段";
      });

    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateTime(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addTime(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      if (row.count !== 0) {
        this.$modal.msgWarning("该时间段已有人报名，请清除后再删除！");
        return;
      }
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除时间段编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delTime(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('lxy/time/export', {
        ...this.queryParams
      }, `time_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>


<style >
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}

.dashboard-editor-container {
  /* background-color: rgb(240, 242, 245); */
  display: flex;
  /*使用Flexbox布局*/
  width: 100%;
}

.chart-wrapper {
  background: #ffffff;
  padding: 16px 16px 0;
  width: 75%;
  margin-right: 20px;
}

@media (max-width:1024px) {
  .chart-wrapper {
    padding: 8px;
  }
}
.custom-row {
  margin-top: 15px; /* 调整行之间的顶部间距 */
  margin-bottom: 15px; /* 调整行之间的底部间距 */
}

</style>